#include "Maze.h"
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <utility>

void Maze::init() {
    height = 0;
    width = 0;
    is_load = false;
}

bool Maze::loadMap(const std::string& file_name) {
    std::ifstream file(file_name);
    if (!file.is_open()) {
        std::cerr << "文件读取失败" << std::endl;
        return false;
    }

    file >> height >> width;  // 读取高和宽
    if (file.fail()) {
        std::cout << "读取高和宽失败" << std::endl;
        return false;
    }

    std::cout << "地图尺寸 高:" << height << " 宽:" << width << std::endl;
    map.resize(height, std::vector<int>(width));  // 行=height，列=width
    std::cout << "地图数据如下:\n";

    for (int row = 0; row < height; row++) {  // 遍历每一行
        for (int col = 0; col < width; col++) {  // 遍历当前行的每一列
            if (!(file >> map[row][col])) {
                std::cerr << "读取地图文件出错" << std::endl;
                return false;
               
            }
            if(map[row][col]<-2 || map[row][col]>3)
                {
                    std::cout<<"出现不合法的数据"<<std::endl;
                    return false;
                }
            std::cout << map[row][col] << " ";
        }
        std::cout << "\n";
    }
    is_load = true;
    return true;
}

bool Maze::isWall(int h, int w) { 
    // 先判断是否越界，越界视为墙
    if (h < 0 || h >= height || w < 0 || w >= width) {
        return true;  
    }
    return false;
}

std::pair<int, int> Maze::setStart() {
    if (!is_load) {
        std::cerr << "没有导入地图文件,返回(-1,-1)" << std::endl;
        return {-1, -1};
    }
    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            if (map[row][col] == -1) {  // 找到起点
                std::cout << "找到起点,位置是[" << row+1 << "," << col+1 << "]" << std::endl;  // 建议加逗号和换行
                return {row, col};
            }
        }
    }
    // 未找到起点时返回无效坐标
    std::cout << "未找到起点,返回(-1,-1)" << std::endl;
    return {-1, -1};
}

std::pair<int, int> Maze::setEnd() {
    if (!is_load) {
        std::cerr << "没有导入地图文件,返回(-1,-1)" << std::endl;
        return {-1, -1};  // 补充返回值
    }
    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            if (map[row][col] == -2) {  // 找到终点
                std::cout << "找到终点,位置是[" << row+1 << "," << col+1 << "]" << std::endl;  // 修正提示信息
                return {row, col};
            }
        }
    }
    // 未找到终点时返回无效坐标
    std::cout << "未找到终点" << std::endl;
    return {-1, -1};
}